﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AESEncrypt;
using ZIP;
using RSA文件加密;
using System.Security.Cryptography;
using System.IO.Compression;
using System.Data.SqlClient;
using System.Data.OleDb;
using Microsoft.VisualBasic;
using System.Web.Security;
using System.Security.Cryptography.X509Certificates;
using FtpClient.Properties;
using System.Text.RegularExpressions;
using System.Threading;
namespace FtpClient
{

    public partial class MainForm : Form
    {
        private FtpHelper ftpHelper;

        private  DateTime clickTime;

        private bool isClicked = false;

        public string getPub { get; set; }
        public string getInfoName { get; set; }
        public string getipAddr  { get; set; }
        public string getport { get; set; }
        public string getuserName  { get; set; }
        public string getpassword  { get; set; }

        //初始化密钥向量
        private static string _aesKeyVector = "q2T_=R/*33vc";

        public MainForm()
        {
            InitializeComponent();
        }

        #region 初始化加载事件

        /// <summary>
        /// 初始化界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            InitTreeView();
            //save();
        }

        private void InitTreeView()
        {
            string[] drives = Environment.GetLogicalDrives();
            int i = 0;
            foreach (string drive in drives)
            {
                DriveInfo d = new DriveInfo(drive);
                if ((d.DriveType & DriveType.Fixed) == DriveType.Fixed)
                {
                    string drive1 = drive.Substring(0, drive.Length - 1);
                    this.treeLocal.Nodes[0].Nodes.Add(drive1);
                    this.treeLocal.Nodes[0].Nodes[i].ImageIndex = 1;
                    this.treeLocal.Nodes[0].Nodes[i].SelectedImageIndex = 1;
                    this.treeLocal.Nodes[0].Nodes[i].Tag = drive1;
                    this.treeLocal.Nodes[0].Nodes[i].Nodes.Add("");//增加一个空白节点，看起来是加号
                    i++;
                }
            }
        }

        #endregion

        #region 菜单栏及工具栏

        private void menuAbout_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }

        private void menuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void menuLogin_Click(object sender, EventArgs e)
        {
            //this.btnLogin_Click(null, null);
            ListDirectory();
        }

        /// <summary>
        /// 前一个目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbtnPre_Click(object sender, EventArgs e)
        {
            //如果就目录,先设置上级目录，再列出目录
            ftpHelper.SetPrePath();
            this.ListDirectory();
        }

        #endregion

        #region FTP操作功能

        /// <summary>
        /// 登录时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       


        /// <summary>
        /// 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTmp_DoubleClick(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            FtpContentType contentType;
            if (Enum.TryParse(btnTmp.Tag.ToString(), out contentType)) {
                switch (contentType) {
                    case FtpContentType.folder:
                        //如果是目录
                        ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, btnTmp.Text);
                        this.ListDirectory();//再次列出目录
                        break;
                    default:
                        MessageBox.Show("非目录，请点击右键","提示",MessageBoxButtons.OK);
                        break;
                }
            }
        }


        /// <summary>
        /// 列出目录
        /// </summary>
        private void ListDirectory()
        {
            bool isOk = false;
            Regex reg = new Regex("\\^En\\.zip$");//判断加密文件与否
            string[] arrAccept = ftpHelper.ListDirectory(out isOk);//调用Ftp目录显示功能
            if (isOk)
            {
                this.ListFtpPanel.Controls.Clear();
                foreach (string accept in arrAccept)
                {
                    string name = accept.Substring(39);
                    Button btnTmp = new Button()
                    {
                        BackColor = Color.White,
                        TextImageRelation = TextImageRelation.ImageAboveText,
                        Name = name,
                        Text = name,
                        Width = 100,
                        Height = 100
                    };
                    btnTmp.FlatAppearance.BorderSize = 0;
                    btnTmp.FlatStyle = FlatStyle.Flat;
                    if (accept.IndexOf("<DIR>") != -1)
                    {
                        btnTmp.Image = global::FtpClient.Properties.Resources.folder.ToBitmap();
                        btnTmp.Tag = FtpContentType.folder;
                    }
                    else {
                        if (reg.IsMatch(name) == true)
                        {
                            //btnTmp.Text = name.Length>20?name.Substring(0,20)+"...":name;
                            btnTmp.Image = global::FtpClient.Properties.Resources.jiamitubiao.ToBitmap();
                        }
                        else
                        {
                            btnTmp.Image = global::FtpClient.Properties.Resources.file.ToBitmap();
                        }
                        btnTmp.Tag = FtpContentType.file;
                        btnTmp.ContextMenuStrip = menuRightKey;
                        btnTmp.MouseDown += new MouseEventHandler(BtnTmp_MouseDown);
                    }
                    btnTmp.Click += new EventHandler(btnTmp_Click);//此处由于双击事件被屏蔽，所以用单击事件模拟双击
                    this.ListFtpPanel.Controls.Add(btnTmp);            
                }
                lblMsg.Text = "列出目录成功";
            }
            else {
                ftpHelper.SetPrePath();
                lblMsg.Text = "链接失败，或者没有数据";
            }
        }

        private void BtnTmp_MouseDown(object sender, MouseEventArgs e)
        {
            //如果是右键按下
            if (e.Button == MouseButtons.Right)
            {
                Button btnTmp = (Button)sender;
                string name = btnTmp.Text;
                this.menuSaveAs.Tag = name;
                this.menuDelete.Tag = name;
            }
        }

        private void btnTmp_Click(object sender, EventArgs e)
        {
            if (isClicked)
            {
                TimeSpan span = DateTime.Now - clickTime;
                if (span.Milliseconds < SystemInformation.DoubleClickTime)
                {
                    btnTmp_DoubleClick(sender, e);
                    isClicked = false;
                }
            }
            else
            {
                isClicked = true;
                clickTime = DateTime.Now;
            }
        }

        #endregion

        #region 树菜单事件

        /// <summary>
        /// 展开之前操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLocal_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Level > 0) {
                //点击之前，先填充节点：
                string path = e.Node.FullPath.Substring(e.Node.FullPath.IndexOf("\\")+1)+"\\";
                e.Node.Nodes.Clear();
                //string path = string.Format("{0}{1}",e.Node.Tag,this.treeLocal.PathSeparator);
                string[] files= Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly);
                int i = 0;
                foreach (string file in files) {
                    FileInfo f = new FileInfo(file);
                    if ((f.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (f.Attributes & FileAttributes.System) != FileAttributes.System)
                    {
                        e.Node.Nodes.Add(Path.GetFileName(file));
                        e.Node.Nodes[i].ImageIndex = 3;
                        e.Node.Nodes[i].SelectedImageIndex = 3;
                        e.Node.Nodes[i].Tag = file;
                        i++;
                    }
                }
                string[] dirs=  Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
                foreach (string dir in dirs)
                {
                    DirectoryInfo d = new DirectoryInfo(dir);
                    if ((d.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (d.Attributes & FileAttributes.System) != FileAttributes.System)
                    {
                        e.Node.Nodes.Add(Path.GetFileName(dir));
                        e.Node.Nodes[i].ImageIndex = 2;
                        e.Node.Nodes[i].SelectedImageIndex = 2;
                        e.Node.Nodes[i].Tag = dir;
                        e.Node.Nodes[i].Nodes.Add("");//增加一个空白节点，看起来是加号
                        i++;
                    }
                }
            }
        }

        /// <summary>
        /// 选中后，右键事件判断，只有文件类型，右键才可用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLocal_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level > 0 && e.Node.ImageIndex == 3)
            {
                this.menuLoad.Visible = true;
                this.MenuLoadWithout.Visible = true;
               // this.MenuLoadWithout.Enabled = true;
                //this.menuLocal.Enabled = true;
                string path = e.Node.FullPath.Substring(e.Node.FullPath.IndexOf("\\") + 1);
                this.menuLoad.Tag = path;
                this.MenuLoadWithout.Tag = path;
            }
            else {
               // this.menuLocal.Enabled = false;
                this.menuLoad.Visible = false;
                this.MenuLoadWithout.Visible = false;
            }
        }

        #endregion

        #region 右键事件


        /// <summary>
        /// 右键另存为按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuSaveAs_Click(object sender, System.EventArgs e)
        {
            

            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
            string name = menuItem.Tag.ToString();
            Regex reg = new Regex("\\^En\\.zip$");//判断加密文件与否
            if (reg.IsMatch(name) == true)
            {
             
                #region 选择私钥文件
                MessageBox.Show("请先选择私钥文件");
                string PrivateKey = "";
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//no多选
                dialog.Title = "请选择私钥文件";
                dialog.Filter = "文本文件(*.txt))|*.txt";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = dialog.FileName;
                    StreamReader sr3 = new StreamReader(path, Encoding.Default);
                    PrivateKey = sr3.ReadLine();
                    sr3.Close();
                }
                else
                {
                    return;
                }
                #endregion
                SaveFileDialog sfd = new SaveFileDialog()
                {
                    FileName = name,
                    Filter="All Files|(*.*)",
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                    Title="另存为"
                };
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //下载文件
                string filePath = sfd.FileName;
                string fileName = Path.GetFileName(filePath);
                string mima = "";
               
                //MessageBox.Show(filePath+"*****"+fileName);
                ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, fileName);
                bool isOk = true;
                ftpHelper.DownLoad(filePath, out isOk);
                if (isOk)
                {
                    lblMsg.Text = "下载失败";
                }
                else
                {
                    lblMsg.Text = "下载成功";
                }
                ftpHelper.SetPrePath();
                #region  解压文件
                if (filePath.EndsWith(".zip"))
                {
                    RSA2 rSA = new RSA2();
                    ZipHelpClass zhc = new ZipHelpClass();
                    var file = new FileInfo(filePath);
                    int length1 = filePath.Length;
                    int length2 = file.Name.Length;
                    var fpath = filePath.Substring(0, length1 - length2); //获取当前目录
                    //zhc.ZipToFile(filePath, fpath);//解压文件
                    try
                    {
                        ZipFile.ExtractToDirectory(filePath, fpath);
                    }
                    catch
                    {
                        MessageBox.Show("文件已存在！下载失败！");
                    }
                    string zippath = filePath;

                    //更换名字
                    filePath = filePath.Remove(filePath.Length - 4, 4);
                    filePath = filePath.Replace("^", ".");
                    Regex reg2 = new Regex("\\(user：.+\\)");
                    filePath = reg2.Replace(filePath, "");
  
                    var txtpath = filePath + ".txt";//密钥文件

                    //string priPath = "D:\\小谢新建的文件夹\\密钥.txt";//RSA密钥文件位置


                    /*StreamReader sr3 = new StreamReader(priPath, Encoding.Default);
                    PrivateKey = sr3.ReadLine();*/

                    // MessageBox.Show(PrivateKey);


                    try
                    {
                        rSA.Decrypt(txtpath, filePath + "de.txt", PrivateKey);
                        StreamReader sr4 = new StreamReader(filePath + "de.txt", Encoding.Default);
                        mima = sr4.ReadLine();
                        sr4.Close();

                    }
                    catch
                    {
                        MessageBox.Show("私钥错误！");
                        File.Delete(txtpath);//删除密钥文件
                        File.Delete(filePath + "de.txt");
                        File.Delete(filePath);
                        File.Delete(zippath);//删除zip文件
                        MessageBox.Show("下载失败！");
                        return;
                    }

                    File.Delete(txtpath);//删除密钥文件
                    File.Delete(filePath + "de.txt");
                    File.Delete(zippath);//删除zip文件

                }

                #endregion
                //**********************************
                #region  解密
                string KeyVector = _aesKeyVector;//密钥向量
                string filePath2;

                filePath2 = filePath;

                //MessageBox.Show(filePath, "原来");

                if (filePath.EndsWith(".En"))
                {
                    filePath = filePath.Remove(filePath.Length - 3, 3);

                    //MessageBox.Show(filePath, "现在");

                    FileStream sr = new FileStream(filePath2, FileMode.Open, FileAccess.Read);
                    FileStream sw = new FileStream(filePath, FileMode.Create, FileAccess.Write);

                    if (sr.Length > 50 * 1024 * 1024)//如果文件大于50M，采取分块解密，按50MB读写
                    {
                        byte[] mybyte = new byte[52428816];//解密缓冲区50MB+16B
                        byte[] decrpt = new byte[52428800];//解密后的50MB
                        int numBytesRead = 52428816;//每次解密的流大小
                        long leftBytes = sr.Length;//剩余需要解密的流大小
                        long readBytes = 0;//已经读取的流大小
                        try
                        {
                            while (true)
                            {
                                if (leftBytes > numBytesRead)
                                {
                                    sr.Read(mybyte, 0, mybyte.Length);
                                    decrpt = AES_EnorDecrypt.AESDecrypt(mybyte, mima, KeyVector);
                                    sw.Write(decrpt, 0, decrpt.Length);
                                    leftBytes -= numBytesRead;
                                    readBytes += numBytesRead;

                                }
                                else//重新设定读取流大小，避免最后多余空值
                                {
                                    byte[] newByte = new byte[leftBytes];
                                    sr.Read(newByte, 0, newByte.Length);
                                    byte[] newWriteByte;
                                    newWriteByte = AES_EnorDecrypt.AESDecrypt(newByte, mima, KeyVector);
                                    sw.Write(newWriteByte, 0, newWriteByte.Length);
                                    readBytes += leftBytes;

                                    break;
                                }
                            }
                        }
                        catch
                        {
                            sr.Close();
                            sw.Close();
                            File.Delete(filePath2);
                            // e.Cancel = true;
                        }
                        sr.Close();
                        sw.Close();
                    }
                    else
                    {
                        byte[] mybyte = new byte[(int)sr.Length];
                        sr.Read(mybyte, 0, (int)sr.Length);
                        try
                        {
                            mybyte = AES_EnorDecrypt.AESDecrypt(mybyte, mima, KeyVector);
                            sw.Write(mybyte, 0, mybyte.Length);

                        }
                        catch
                        {
                            sr.Close();
                            sw.Close();
                            MessageBox.Show("密钥错误!");
                            File.Delete(filePath);
                            File.Delete(filePath2);
                            MessageBox.Show("下载失败！");
                            return;
                            //  e.Cancel = true;
                        }
                        sr.Close();
                        sw.Close();
                    }
                #endregion

                    File.Delete(filePath2);
                    MessageBox.Show("下载成功！");

                }
                }
            }
                else
                {
                    SaveFileDialog sfd2 = new SaveFileDialog()
                    {
                        FileName = name,
                        Filter = "All Files|(*.*)",
                        InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                        Title = "另存为"
                    };
                    if (sfd2.ShowDialog() == DialogResult.OK)
                    {
                        //下载文件
                        string filePath = sfd2.FileName;
                        string fileName = Path.GetFileName(filePath);
                        ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, fileName);
                        bool isOk = false;
                        ftpHelper.DownLoad(filePath, out isOk);
                        if (isOk)
                        {
                            lblMsg.Text = "下载失败";
                          
                        }
                        else
                        {
                            lblMsg.Text = "下载成功";
                            MessageBox.Show("下载成功！");
                        }
                        ftpHelper.SetPrePath();
                    }
                }
               
             
            
        }

        /// <summary>
        /// 右键删除功能FTP上的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuDelete_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
            DialogResult dr = MessageBox.Show("确认删除 " + menuItem.Tag.ToString() + " 吗？","提示",MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                string name = menuItem.Tag.ToString();
                ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, name);
                bool isOk = false;
                ftpHelper.DeleteFile(out isOk);
                ftpHelper.SetPrePath();
                if (isOk)
                {
                    this.ListDirectory();
                    lblMsg.Text = "删除成功";
                }
                else
                {
                    lblMsg.Text = "删除失败";
                }
            }

        }
    
        /// <summary>
        /// 本地文件上传事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuLoad_Click(object sender, EventArgs e)
        {

            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            try
            {
                string path = mi.Tag.ToString();
                //***************************************************************

                string KeyVector = _aesKeyVector;//密钥向量
                //string path = Path.GetDirectoryName(textBox3.Text);
                //string name = Path.GetFileName(textBox3.Text);


                string mima="";
                string filePath2;
                filePath2 = path;
                mima = Guid.NewGuid().ToString();//随机生成密钥;
                string Pub = getPub;
                #region 读取RSA公钥
                string PublicKey;
                string AceptName;
                ftpForm1 nf = new ftpForm1();
                nf.Owner = this;
                nf.ShowDialog();
                AceptName = getInfoName;
                PublicKey = getPub;
                if (nf.DialogResult != DialogResult.OK) return;
                //if (getPub=="") return;
               // MessageBox.Show(getPub);
                //MessageBox.Show(Pub);
                #endregion

                #region   加密        
                FileStream sr = new FileStream(path, FileMode.Open, FileAccess.Read);

                path += ".En";
                FileStream sw = new FileStream(path, FileMode.Create, FileAccess.Write);
                //MessageBox.Show(mima);
                if (sr.Length > 50 * 1024 * 1024)//如果文件大于50M，采取分块加密，按50MB读写
                {
                    byte[] mybyte = new byte[52428800];//每50MB加密一次                  
                    int numBytesRead = 52428800;//每次加密的流大小
                    long leftBytes = sr.Length;//剩余需要加密的流大小
                    long readBytes = 0;//已经读取的流大小
                    //每50MB加密后会变成50MB+16B
                    byte[] encrpy = new byte[52428816];
                    while (true)
                    {
                        if (leftBytes > numBytesRead)
                        {
                            sr.Read(mybyte, 0, mybyte.Length);
                            encrpy = AES_EnorDecrypt.AESEncrypt(mybyte, mima, KeyVector);
                            sw.Write(encrpy, 0, encrpy.Length);
                            leftBytes -= numBytesRead;
                            readBytes += numBytesRead;
                            //backgroundWorker1.ReportProgress((int)(readBytes * 100 / sr.Length));
                        }
                        else//重新设定读取流大小，避免最后多余空值
                        {
                            byte[] newByte = new byte[leftBytes];
                            sr.Read(newByte, 0, newByte.Length);
                            byte[] newWriteByte;
                            newWriteByte = AES_EnorDecrypt.AESEncrypt(newByte, mima, KeyVector);
                            sw.Write(newWriteByte, 0, newWriteByte.Length);
                            readBytes += leftBytes;
                            // backgroundWorker1.ReportProgress((int)(readBytes * 100 / sr.Length));
                            break;
                        }
                    }
                }
                else
                {
                    byte[] mybyte = new byte[sr.Length];
                    sr.Read(mybyte, 0, (int)sr.Length);
                    mybyte = AES_EnorDecrypt.AESEncrypt(mybyte, mima, KeyVector);
                    sw.Write(mybyte, 0, mybyte.Length);
                    // backgroundWorker1.ReportProgress(100);
                }

                sr.Close();
                sw.Close();
                #endregion
                
                #region 创建文件夹，移动文件,压缩文件
                var filepath = path;
                var filepath2 = path+".txt"; //新建txt文件
                var file = new FileInfo(filepath);
                var file2 = new FileInfo(filepath2);
                int length1 = filepath.Length;
                int length2 = file.Name.Length;
                var fpath = filepath.Substring(0,length1 - length2); //获取当前目录
                var newfilepath = fpath + "(user：" + AceptName + ")" + file.Name.Replace(".", "^");
               // var newfilepath = fpath + file.Name.Substring(0,file.Name.IndexOf("."))+"_txt";
               // MessageBox.Show(newfilepath);
                var destFileName = newfilepath + "\\" + file.Name;
                var destFileName2 = newfilepath + "\\" + file2.Name;
                if (!Directory.Exists(newfilepath))
                {
                    Directory.CreateDirectory(newfilepath);
                }//**************存储随机AES密钥
                if (!File.Exists(filepath2))
                {
                    FileStream fs1 = new FileStream(filepath2, FileMode.Create, FileAccess.Write);//创建写入文件 
                    StreamWriter sw2 = new StreamWriter(fs1);
                    sw2.WriteLine(mima);//开始写入值
                    sw2.Close();
                    fs1.Close();
                }
                else
                {
                    FileStream fs = new FileStream(filepath2, FileMode.Open, FileAccess.Write);
                    StreamWriter sr2 = new StreamWriter(fs);
                    sr2.WriteLine(mima);//开始写入值
                    sr2.Close();
                    fs.Close();

                }
                //rsa********8
                
                RSA2 rSA = new RSA2();
              
                /*
                string pubPath = "D:\\小谢新建的文件夹\\公钥.txt";//要加密文件绝对路径

                StreamReader sr3 = new StreamReader(pubPath, Encoding.Default);
                PublicKey = sr3.ReadLine();
                */
                

                // MessageBox.Show(PublicKey);
                string strPath = filepath2;//要加密文件绝对路径
                string desPath = filepath2;//要加密文件绝对路径
                
                desPath += "(加密).txt";
              
           
                rSA.Encrypt(strPath, desPath, PublicKey);
                
                //************
                File.Copy(filepath, destFileName);
                File.Copy(desPath, destFileName2);

                ZipHelpClass zhc = new ZipHelpClass();
                zhc.DirectoryToZip(newfilepath, fpath);//压缩文件
     
                File.Delete(destFileName);
                File.Delete(destFileName2);
                File.Delete(filepath);
                File.Delete(filepath2);
                File.Delete(desPath);
                Directory.Delete(newfilepath);

                path = newfilepath + ".zip";
                #endregion
                

                //******************************************************
                
                if (File.Exists(path))
                {
                    try
                    {
                        ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, Path.GetFileName(path));
                        bool isOk = false;
                        ftpHelper.UpLoad(path, out isOk);
                        ftpHelper.SetPrePath();

                        if (isOk)
                        {
                            this.ListDirectory();
                            lblMsg.Text = "上传成功";
                            MessageBox.Show("上传成功！");
                        }
                        else
                        {
                            lblMsg.Text = "上传失败";
                            MessageBox.Show("上传失败！");
                        }
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show("还未登录！", "提示");
                    }
                    File.Delete(path);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请先单击选中目标文件再上传！", "提示");
            }
        }

        #endregion
        private void MenuLoadWithout_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            string path = mi.Tag.ToString();
            if (File.Exists(path))
            {
                ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, Path.GetFileName(path));
                bool isOk = false;
                ftpHelper.UpLoad(path, out isOk);
                ftpHelper.SetPrePath();
                if (isOk)
                {
                    this.ListDirectory();
                    lblMsg.Text = "上传成功";
                }
                else
                {
                    lblMsg.Text = "上传失败";
                }
            }
        }

        private void lblWelcome_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
          /*  Form1 form1 = new Form1();
            form1.Show();*/
        }
       

        //



        //自动下载shujuku
        private void button4_Click(object sender, EventArgs e)
        {
            ftpForm1 nf = new ftpForm1();
            nf.Owner = this;
            nf.ShowDialog();
        }

        #region 将数据库文件上传至服务器
        public void upload()
        {
            string ipAddr = "192.168.80.1";
            string port = "2121";
            string userName = "test1";
            string password = "123456";
            string path = "D:\\testData.zip";
            ftpHelper = new FtpHelper(ipAddr, port, userName, password);
            sign();
            if (File.Exists(path))
            {
               /* try
                {*/
              
                    ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, "server\\" + Path.GetFileName(path));
                    bool isOk = false;
                    ftpHelper.UpLoad(path, out isOk);
                    ftpHelper.SetPrePath();

                    if (isOk)
                    {
                        //this.ListDirectory();
                        lblMsg.Text = "上传成功";
                        //MessageBox.Show("上传成功！");
                    }
                    else
                    {
                        lblMsg.Text = "上传失败";
                        MessageBox.Show("上传失败！");
                    }
                    File.Delete(path);
                    ftpHelper.SetPrePath();
                /*}

                catch (Exception ex)
                {
                    MessageBox.Show("出错了！", "提示");
                }*/
                //File.Delete(path);
            }
            else
            {
                MessageBox.Show("本地数据库丢失！", "提示");
            }
        }
        #endregion

        #region 将数据库下载至本地
        public void save()
        {
            string ipAddr = "192.168.80.1";
            string port = "2121";
            string userName = "test1";
            string password = "123456";
            ftpHelper = new FtpHelper(ipAddr, port, userName, password);

            string filePath = "D:\\testData.zip";
            string fileName = Path.GetFileName(filePath);
            fileName = "server\\" + fileName;
            try
            {
                ftpHelper.RelatePath = string.Format("{0}/{1}", ftpHelper.RelatePath, fileName);
                bool isOk = true;
                ftpHelper.DownLoad(filePath, out isOk);
                if (isOk)
                {
                    lblMsg.Text = "下载失败";
                }
                else
                {
                    lblMsg.Text = "下载成功";
                }
            }
            catch
            {
                MessageBox.Show("服务器数据库丢失!");
            }
            ftpHelper.SetPrePath();
            if (signCheck() == false) MessageBox.Show("数据库内容被篡改!");
;
        }
        #endregion

      
        //数字签名
        public void sign()
        {
            string fileName = "D:\\test1.mdb";
            string filepath = "D:\\test1-sign.txt";
            string signPri = "<RSAKeyValue><Modulus>z691SWR0knMo88D9RcCQfzUVl5fJc4D26IwVhqN9NDVHfOnKRCngeYsmHzkDbRXN5DZfr8y/Ew0qHSa+dXFDT4RjGl01yCLHQTe9hy3gazmjAv1CUxiGcEPiD7EKtruTEw7O21ZUCi+CYaEclEW/UH93gslT9FLqzeyVrnZsQuE=</Modulus><Exponent>AQAB</Exponent><P>8Hf/LWjkSvK+WDTDdw+Mbg/Vb10q8lPsi71OS/uiHIveIqNibxmNsCUt81S3FWkqEL3m1XAuWNTFMFyjKXbzHw==</P><Q>3RlooD6aolKNwmcnXBeURjIJCJApXfZsKfVqTpNRIYbNjAlYIH9+m1WqV6sIT397aSKBvwnAm5iTUmf+PRwJ/w==</Q><DP>V9Ga8XyDExP/i7sJP2wAPxmtOtRtoL4hfw8NjxZAp+g0obXFdwmAAzoww9LGYh1b7W1M5dnoMyzRLs5GEBiOxQ==</DP><DQ>UOMCy90bZVceVYi3dZGKxUN42pEjESUd3RvTkHuEqudOO3UPsJP0FY/5iakgmTTiSUw+e01uEX54JyW0dVbUsQ==</DQ><InverseQ>XlZZt6eQZwPrbTQC9uV1dfta4Cp2c9p2D8eZnez2xuYvAGpk/yKdX6dFeUdPedq+u9YtYsM9zoP6TXffpc22oQ==</InverseQ><D>ATrEsv6JQiS0ZV0LItKVCGvECPW5F5n33ECYEAf/wcNe/PpVXDnzPkT4oM6xmn+6jFNWFbBcoTw+t5V3IzLcdyVR8ICxEvXiIxVdEZPn7O0FOjYf3rJIyMrqtNVJPksL65DCIveKO96RvNppqUj7fF+4GUueztFUZNGPj0g8vRE=</D></RSAKeyValue>";
            string signPub = "<RSAKeyValue><Modulus>z691SWR0knMo88D9RcCQfzUVl5fJc4D26IwVhqN9NDVHfOnKRCngeYsmHzkDbRXN5DZfr8y/Ew0qHSa+dXFDT4RjGl01yCLHQTe9hy3gazmjAv1CUxiGcEPiD7EKtruTEw7O21ZUCi+CYaEclEW/UH93gslT9FLqzeyVrnZsQuE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            string newfilepath = "D:\\testData";
            RSAsign sign = new RSAsign();
            string dd = sign.FileToBinary(fileName);
            string signTxt = sign.Sign(dd, signPri); //数字签名
            //签名
            FileStream fs1 = new FileStream(filepath, FileMode.Create, FileAccess.Write);//创建写入文件 
            StreamWriter sw2 = new StreamWriter(fs1);
            sw2.WriteLine(signTxt);//开始写入值
            sw2.Close();
            fs1.Close();

            if (!Directory.Exists(newfilepath))
            {
                Directory.CreateDirectory(newfilepath);
            }//**************存储随机AES密钥
            string destFileName = newfilepath + "\\test1.mdb";
            string destFileName2 = newfilepath + "\\test1-sign.txt";
            File.Copy(fileName, destFileName);
            File.Copy(filepath, destFileName2);
            ZipHelpClass zhc = new ZipHelpClass();
            zhc.DirectoryToZip(newfilepath, "D:\\");
            File.Delete(destFileName);
            File.Delete(destFileName2);
            Directory.Delete(newfilepath);
            File.Delete(filepath);
            //File.Delete(newfilepath+".zip");
        }


        //验证数字签名
        public bool signCheck()
        {
            string fileName = "D:\\test1.mdb";
            string fileName2 = "D:\\test1-sign.txt";
            string filePath = "D:\\testData.zip";
            string fpath = "D:\\";
            string signPri = "<RSAKeyValue><Modulus>z691SWR0knMo88D9RcCQfzUVl5fJc4D26IwVhqN9NDVHfOnKRCngeYsmHzkDbRXN5DZfr8y/Ew0qHSa+dXFDT4RjGl01yCLHQTe9hy3gazmjAv1CUxiGcEPiD7EKtruTEw7O21ZUCi+CYaEclEW/UH93gslT9FLqzeyVrnZsQuE=</Modulus><Exponent>AQAB</Exponent><P>8Hf/LWjkSvK+WDTDdw+Mbg/Vb10q8lPsi71OS/uiHIveIqNibxmNsCUt81S3FWkqEL3m1XAuWNTFMFyjKXbzHw==</P><Q>3RlooD6aolKNwmcnXBeURjIJCJApXfZsKfVqTpNRIYbNjAlYIH9+m1WqV6sIT397aSKBvwnAm5iTUmf+PRwJ/w==</Q><DP>V9Ga8XyDExP/i7sJP2wAPxmtOtRtoL4hfw8NjxZAp+g0obXFdwmAAzoww9LGYh1b7W1M5dnoMyzRLs5GEBiOxQ==</DP><DQ>UOMCy90bZVceVYi3dZGKxUN42pEjESUd3RvTkHuEqudOO3UPsJP0FY/5iakgmTTiSUw+e01uEX54JyW0dVbUsQ==</DQ><InverseQ>XlZZt6eQZwPrbTQC9uV1dfta4Cp2c9p2D8eZnez2xuYvAGpk/yKdX6dFeUdPedq+u9YtYsM9zoP6TXffpc22oQ==</InverseQ><D>ATrEsv6JQiS0ZV0LItKVCGvECPW5F5n33ECYEAf/wcNe/PpVXDnzPkT4oM6xmn+6jFNWFbBcoTw+t5V3IzLcdyVR8ICxEvXiIxVdEZPn7O0FOjYf3rJIyMrqtNVJPksL65DCIveKO96RvNppqUj7fF+4GUueztFUZNGPj0g8vRE=</D></RSAKeyValue>";
            string signPub = "<RSAKeyValue><Modulus>z691SWR0knMo88D9RcCQfzUVl5fJc4D26IwVhqN9NDVHfOnKRCngeYsmHzkDbRXN5DZfr8y/Ew0qHSa+dXFDT4RjGl01yCLHQTe9hy3gazmjAv1CUxiGcEPiD7EKtruTEw7O21ZUCi+CYaEclEW/UH93gslT9FLqzeyVrnZsQuE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            RSAsign sign = new RSAsign();

            //string signTxt = sign.Sign(dd, signPri);
            if (File.Exists(fileName)) File.Delete(fileName);
            if (File.Exists(fileName2)) File.Delete(fileName2);
            ZipFile.ExtractToDirectory(filePath, fpath);
            string fileData = sign.FileToBinary(fileName);

            //验证签名
            StreamReader sr4 = new StreamReader(fileName2, Encoding.Default);
            string signTxt2 = sr4.ReadLine();
            sr4.Close();
            if (sign.SignCheck(fileData, signTxt2, signPub) == true)
            {
                File.Delete(filePath);
                File.Delete(fileName2);
                return true;
            }
            else
            {
                File.Delete(filePath);
                File.Delete(fileName2);
                return false;
            }
        }

        private void toolStripProgressBar1_Click(object sender, EventArgs e)
        {

        }

      

        private void menuRef_Click(object sender, EventArgs e)
        {

        }

        private void menuReg_Click_1(object sender, EventArgs e)
        {

        }

        //用户登录
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
           /* Thread thread01 = new Thread(Log);
            thread01.Start();*/
            LogForm log = new LogForm();
            log.Owner = this;
            log.ShowDialog();
            try
            {
                if (log.DialogResult == DialogResult.OK)
                {
                    string ipAddr = getipAddr;
                    string port = getport;
                    string userName = getuserName;
                    string password = getpassword;
                    ftpHelper = new FtpHelper(ipAddr, port, userName, password);
                    ListDirectory();
                    BtLog.Enabled = false;
                    BtReg.Enabled = true;
                    BtRev.Enabled = true;
                    BtRfre.Enabled = true;
                    BtLeave.Enabled = true;
                    BtReturn.Enabled = true;
                    this.menuLocal.Enabled = true;
                    MenuLoadWithout.Enabled = true;
                    menuLoad.Enabled = true;
                    MessageBox.Show("登陆成功！", "提示");
                    Properties.Settings.Default.ipAddress = ipAddr;
                    Properties.Settings.Default.passWord = password;
                    Properties.Settings.Default.port = port;
                    Properties.Settings.Default.userName = userName;
                    Properties.Settings.Default.Save();

                }
            }
            catch
            {
                MessageBox.Show("登陆失败！", "提示");
            }
           // thread01.Abort();
        }
        private  void Log()
        {
           MessageBox.Show("123");
           
        }

        //注册公钥
        private void RegButton_Click(object sender, EventArgs e)
        {
            string userName = getuserName;
            //MessageBox.Show("确认注册" + userName);
            if (string.IsNullOrEmpty(userName))
            {
                MessageBox.Show("请输入登录信息");
                return;
            }
            if (userName == "anonymous")
            {
                MessageBox.Show("匿名用户无法注册公私钥！ 请登录后再注册！","提示");
                return;
            }
            RSA2 rsa = new RSA2();
            string PublicKey = rsa.GetPublicKey();
            string PrivatevKey = rsa.GetPrivateKey();
            string name = userName;
            userName = FormsAuthentication.HashPasswordForStoringInConfigFile(userName, "MD5");
            string con = "Server=192.168.6.1;Database=FtpInfo;uid=testA;pwd=123456";
            string sql = "Insert into UseInfo (用户名,公钥) values('" + userName + "'," + "'" + PublicKey + "')";
            SqlConnection mycon = new SqlConnection(con);
            mycon.Open();
            SqlCommand com = new SqlCommand(sql, mycon);

            try
            {
                SqlDataReader reader = com.ExecuteReader();
                reader.Read();
                reader.Close();
                //保存私钥文件
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "私钥保存至";
                sfd.InitialDirectory = @"C:\";
                sfd.Filter = "文本文件| *.txt";
                sfd.FileName = name + "- PrivateKey.txt";

                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = sfd.FileName;
                    if (path == "")
                    {
                        return;
                    }
                    FileStream fsWrite;
                    using (fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] buffer = Encoding.Default.GetBytes(PrivatevKey);
                        fsWrite.Write(buffer, 0, buffer.Length);
                        fsWrite.Close();
                        //MessageBox.Show("保存成功");                                             
                    }
                }
                else
                {
                    com.CommandText = "delete from UseInfo where 用户名 = '" + userName + "'";
                    SqlDataReader reader2 = com.ExecuteReader();
                    reader2.Read();
                    reader2.Close();
                    mycon.Close();
                    return;
                }
            }
            catch
            {
                mycon.Close();
                MessageBox.Show(name + "用户已存在！","提示");
                return;
            }
            mycon.Close();
            //upload();
            MessageBox.Show("注册成功！");

        }

        private void RevButton_Click(object sender, EventArgs e)
        {
            string con = "Server=192.168.6.1;Database=FtpInfo;uid=testA;pwd=123456";
            SqlConnection mycon = new SqlConnection(con);
            mycon.Open();
            //************读取数据
            string name = getuserName;
            string userName = name;
            if (userName == "anonymous")
            {
                MessageBox.Show("匿名用户无法撤销公私钥！ 请登录后再操作！", "提示");
                return;
            }
            DialogResult dr = MessageBox.Show("         确认撤销 " + userName + " 的公钥数据吗？\n              原私钥文件将会失效！", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                name = FormsAuthentication.HashPasswordForStoringInConfigFile(name, "MD5");
                //odCommand.CommandText = "delete  from FtpUser where 用户名 = " + "'" + name + "'";   //建立读取 C#操作Access之按列读取mdb 
                string sql = "delete  from UseInfo where 用户名 = " + "'" + name + "'";
                SqlCommand com = new SqlCommand(sql, mycon);
                try
                {
                    SqlDataReader reader = com.ExecuteReader();
                    reader.Read();
                    reader.Close();

                    //MessageBox.Show(PublicKey);
                }
                catch
                {

                    mycon.Close();
                    MessageBox.Show("找不到该用户数据！");
                    return;
                }

                mycon.Close();
                //upload();
                MessageBox.Show("撤销成功！");
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            ftpHelper.SetPrePath();
            this.ListDirectory();
        }

        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {
            this.ListDirectory();
        }

        private void BtLeave_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void 用户查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ftpForm1 nf = new ftpForm1();
            nf.Owner = this;
            nf.ShowDialog();
            if (nf.DialogResult != DialogResult.OK) return;
            string name = getInfoName;
            UsersForm nf2 = new UsersForm();
            nf2.Owner = this;
            //nf2.getInfoName = getInfoName;
            nf2.ShowDialog();
        }
        private void button1_Click_2(object sender, EventArgs e)
        {
            ProShow nf = new ProShow();
            nf.ShowDialog();
        }


  
          
    }
}
